package com.atguigu.day04;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//死锁案例
public class DeadLockDemo {
    //死锁就是A拥有A锁，想要B锁，B拥有B锁，想要A锁，两者相互制衡，造成死锁
        private static Object lockA = new Object();
        private static Object lockB = new Object();

    public static void main(String[] args) {
        //进程A拥有A锁
         new Thread(() -> {
             synchronized (lockA){
                 System.out.println(Thread.currentThread().getName()+"已经拥有A锁，想要获取B锁");
                 synchronized (lockB){
                     System.out.println(Thread.currentThread().getName()+"成功获得B锁");
                 }
             }
                 }, "A").start();



        //B拥有B锁
         new Thread(() -> {
             synchronized (lockB){
                 System.out.println(Thread.currentThread().getName()+"已经拥有B锁，想要获取A锁");
                 synchronized (lockA){
                     System.out.println(Thread.currentThread().getName()+"成功获得A锁");
                 }
             }
                 }, "B").start();

    }

//
//    public static void main(String[] args) {
//        Lock lockA = new ReentrantLock();
//        Lock lockB = new ReentrantLock();
//        lockA.lock();
//            new Thread(()->{
//                try{
//                //已经拥有A锁，
//                System.out.println(Thread.currentThread().getName()+"已经拥有A锁，想要获取B锁");
//                //线程睡眠几秒
//                try {
//                    TimeUnit.SECONDS.sleep(2);} catch (InterruptedException e) {throw new RuntimeException(e);}
//                //试图获取B锁
//                    lockB.lock();
//                try {
//                    System.out.println(Thread.currentThread().getName()+"成功获取B锁");
//                }finally {
//                    lockB.unlock();
//                }
//                } finally{
//                    lockA.unlock();
//                }
//            },"A").start();
//
//            //对于线程B
//        lockB.lock();
//        new Thread(() -> {
//            try {
//                //拥有B锁
//                System.out.println(Thread.currentThread().getName()+"已经拥有B锁，想要获取A锁");
//                //线程睡眠几秒
//                try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {throw new RuntimeException(e);}
//            //试图获取A锁
//                lockA.lock();
//                try {
//                    System.out.println(Thread.currentThread().getName()+"成功获取A锁");
//                }finally {
//                    lockA.unlock();
//                }
//
//            }finally {
//                lockB.unlock();
//            }
//        }, "B").start();


    }

